package com.demos.webcommon.缓存;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController("CacheController")
@RequestMapping("cache")
public class controller {
    @Autowired
    private com.demos.webcommon.缓存.service service;

    /**
     * 普通缓存
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Cacheable(cacheNames = "ById1", key = "#root.methodName+'_'+#id")
    public Map<String, Object> get1(@PathVariable String id){
        Map<String, Object> map = service.get(id);
        return map;
    }
    @GetMapping("list")
    @Cacheable(cacheNames = "ById2", key = "#root.methodName+'_list'")
    public List<Map<String, Object>> get2(){
        List<Map<String, Object>> l = service.list();
        return l;
    }

    /**
     * 根据 cacheName 和 key 清除缓存
     * @param request
     * @param id
     * @return
     */
    @GetMapping("update/{id}")
    @CacheEvict(cacheNames = "ById1", key = "'get1_'+#id")
    public int update(HttpServletRequest request, @PathVariable String id){
        String name = request.getParameter("name");
        return service.update(id, name);
    }
}
